package com.photoeditor.demo.ui.adapter.stash;


import android.content.Context;
import android.content.res.Resources;
import android.graphics.Paint;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.base.ComponentContext;
import com.common.base.ui.widget.ripple.RippleRelativeLayout;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.model.bean.EmojiPageBean;
import com.photoeditor.demo.model.event.StickersTurnToFunctionSubscribeEvent;
import com.photoeditor.demo.model.event.StickersTurnToRewardEvent;
import com.photoeditor.demo.model.image.emoji.LocalStickerData;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.sticker.StickerUnlockData;
import com.photoeditor.demo.model.store.module.BaseOnlineManager;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.widget.image.emoji.EmojiArrayAdapter;
import com.photoeditor.demo.ui.widget.sticker.StickerMaskView;
import com.photoeditor.demo.ui.widget.sticker.StickerPanelDownloadView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

//import com.photoeditor.demo.ui.widget.image.StickerGifBarView;

/**
 * Emoji panel 的ViewPager的adapter
 */
public class EmojiPageAdapter extends PagerAdapter {

//	/**
//	 * 页面的数量
//	 */
//	private int mPageNum;

//	/**
//	 * 单行的Emoji数目
//	 */
//	private int mColNum;

    /**
     * ViewPager中GridView的item点击的回调
     */
    private OnItemClickListener mItemClickListener;

    private Context mContext;

    private final int DEFAULT_ITEM_SZIE;
    private final int DEFAULT_EMOJI_SIZE;

    private final int DEFAULT_VERTICAL_SPACING;

    private final int PADDING_TOP;

    public static final int DEFAULT_MARGIN = DeviceUtils.dip2px(ComponentContext.getContext(), 22f);

    /**
     * 引导下载的INDEX 第二页
     */
    private final int GUIDE_INDEX = 1;

//	private int mMode;

    private ArrayList<EmojiPageBean> mData;

    private int mRefreshPosition = -1;

    public StickerBar mStickerBar;

    public interface StickerBar {
        boolean isApply();
    }

//	//default
//	public final static int MODE_DOWNLOAD = 1;
//
//	public final static int MODE_UPDATE = 2;
//
//	public final static int MODE_NONE = 0;

    public EmojiPageAdapter(Context context, ArrayList<EmojiPageBean> data, OnItemClickListener onitemClick, StickerBar stickerBar) {
        mContext = context;
//		mPageNum = pageNum;
//		mColNum = colNum;
        mItemClickListener = onitemClick;
        mStickerBar = stickerBar;
        mData = data;
        Resources res = mContext.getResources();
        DEFAULT_ITEM_SZIE = res.getDimensionPixelSize(R.dimen.default_button_size);
        DEFAULT_EMOJI_SIZE = res.getDimensionPixelSize(R.dimen.image_edit_emoji_item_size);
        DEFAULT_VERTICAL_SPACING = res.getDimensionPixelSize(R.dimen.image_edit_emoji_item_margin);

        PADDING_TOP = res.getDimensionPixelSize(R.dimen.image_edit_emoji_panel_padding_top);
//		mVerticalSpacing = mContext.getResources().getDimensionPixelSize(R.dimen.image_edit_emoji_item_margin);
//		mMode = mode;
    }

    public void setData(ArrayList<EmojiPageBean> data) {
        mData = data;
//		mMode = mode;
    }

    @Override
    public int getCount() {
        if (mData != null) {
            return mData.size();
        }
        return 0;
    }

    private int mGifAutoScrollPosition = -1;

    public void setGifAutoScrollPosition(int gifAutoScrollPosition) {
        mGifAutoScrollPosition = gifAutoScrollPosition;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int index) {
//		if((mMode == MODE_DOWNLOAD || mMode == MODE_UPDATE) && index == GUIDE_INDEX){//这种情况是没有安装的情况
//			EmojiGuideView guide = new EmojiGuideView(mContext);
//			((ViewPager) container).addView(guide);
//			if(mMode == MODE_DOWNLOAD){
//				//do nothing default is download
//			} else{//这种是已经安装需要更新的情况 MODE_UPDATE
//				guide.setMode(MODE_UPDATE);
//			}
//			return guide;
//		} else{
//			GridView view = new GridView(mContext);
//			view.setNumColumns(mColNum);
//			view.setVerticalSpacing(mVerticalSpacing);
//			view.setSelector(R.drawable.emoji_item_selector);
//			int curIndex = index + 1;
//			if(mMode == MODE_UPDATE && index > GUIDE_INDEX){
//				curIndex -= 1;
//			}
//			EmojiArrayAdapter adapter = new EmojiArrayAdapter(mContext, StickerManager.getInstance().getEmojiData(curIndex));
//			view.setAdapter(adapter);
//			view.setOnItemClickListener(mItemClickListener);
//			((ViewPager) container).addView(view);
//			return view;
//		}
        final EmojiPageBean bean = mData.get(index);
//		if(bean.isType(EmojiPageBean.TYPE_RESOURCES) || bean.isType(EmojiPageBean.TYPE_INSTALL_APK) || bean.isType(EmojiPageBean.TYPE_RECENT)){
//			GridView view = new GridView(mContext);
//			view.setGravity(Gravity.CENTER_HORIZONTAL);
//			view.setNumColumns(bean.getColNum());
//			view.setVerticalSpacing(DEFAULT_VERTICAL_SPACING);
//			view.setSelector(R.drawable.emoji_item_selector);
//			EmojiArrayAdapter adapter = new EmojiArrayAdapter(mContext, StickerManager.getInstance().getEmojiData(bean),
//					DEFAULT_ITEM_SZIE, DEFAULT_ITEM_SZIE,
//					DEFAULT_EMOJI_SIZE, DEFAULT_EMOJI_SIZE);
//			view.setAdapter(adapter);
//			view.setOnItemClickListener(mItemClickListener);
//			view.setTag(index);
//			((ViewPager) container).addView(view);
//			return view;
//		} else
        if (bean.isType(EmojiPageBean.TYPE_RESOURCES) || bean.isType(EmojiPageBean.TYPE_INSTALL_APK)
                || bean.isType(EmojiPageBean.TYPE_RECENT) || bean.isType(EmojiPageBean.TYPE_UNINSTALL_APK)
                || bean.isType(EmojiPageBean.TYPE_INSTALL_EMOJI_APK)
                || bean.isType(EmojiPageBean.TYPE_AR_STICKER)
                || bean.isType(EmojiPageBean.TYPE_ONLINE) || bean.isType(11)) {
            RippleRelativeLayout layout = new RippleRelativeLayout(mContext);
//			layout.setBackgroundColor(bean.getBgColor());
            //layout.setPadding(0, PADDING_TOP, 0, 0);
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, bean.getPageHeight());
            lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
            lp.topMargin = DEFAULT_MARGIN;
            GridView view = new GridView(mContext);
            view.setGravity(Gravity.CENTER);
            view.setNumColumns(bean.getColNum());
            view.setVerticalSpacing(bean.getVerticalSpacing());
//			view.setSelector(R.drawable.emoji_item_selector);
            EmojiArrayAdapter adapter = new EmojiArrayAdapter(mContext, LocalStickerData.getInstance().getEmojiData(bean),
                    bean.getItemWidth(), bean.getItemHeight(),
                    bean.getEmojiWidth(), bean.getEmojiHeight());
            view.setAdapter(adapter);
            view.setOnItemClickListener(mItemClickListener);
            layout.setTag(index);
            layout.addView(view, lp);
            if (bean.isType(EmojiPageBean.TYPE_ONLINE)) {
                StickerPanelDownloadView downloadLayout = (StickerPanelDownloadView) View.inflate(mContext, R.layout.layout_sticker_download, null);
                downloadLayout.setData(bean.getPkgName(), BaseOnlineManager.STORE_FUNC_TYPE_STICKER, false);
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, bean.getPageHeight() + DEFAULT_MARGIN);
                layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                layout.addView(downloadLayout, layoutParams);
            } else if (bean.isNeedBuy() && !StickerUnlockData.getInstance().isUnlockSticker(bean.getPkgName())) {
                StickerMaskView maskView = (StickerMaskView) View.inflate(mContext, R.layout.layout_sticker_mask, null);
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
                layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                layout.addView(maskView, layoutParams);
                if (maskView != null) {
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FLOAT_SHOW,
                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_STICKER);

                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                            StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_STICKER,
                            StatisticsConstant.KEY_FILTER_NAME, StatisticsConstant.VALUE_VIP_FUN_STICKER);
                }
                //点击订阅按钮，发消息给EditorImageActivity跳转功能订阅页
                maskView.findViewById(R.id.btn_subscribe).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FLOAT_BUTT_CLICK,
                                StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_STICKER);
                        EventBus.getDefault().post(new StickersTurnToFunctionSubscribeEvent());
                    }
                });
                TextView rewardBtn = maskView.findViewById(R.id.btn_reward);
                rewardBtn.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
                rewardBtn.getPaint().setAntiAlias(true);//抗锯齿
                rewardBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        EventBus.getDefault().post(new StickersTurnToRewardEvent(bean.getPkgName()));
                    }
                });
            }

            container.addView(layout);
            return layout;
//		} else if(bean.isType(EmojiPageBean.TYPE_GUIDE_DOWNLOAD)){
//			View view = View.inflate(mContext, R.layout.layout_emoji_more, null);
//			//((ImageView)view.findViewById(R.id.iv_load_more)).setImageResource(R.drawable.sticker_more_emoji);
//			view.findViewById(R.id.btn_emoji_load_more).setOnClickListener(new View.OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					String url = bean.getDownUrl();
//					if(TextUtils.isEmpty(url)){
//						url = StickerConstant.APK_EMOJI_PKG_NAME_ALL_URL;
//					}
//					ProductDrive.gotoGPStoreOrBrowser(ComponentContext.getContext(), url);
//					StatisticsUtils.statisticsStashClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_STASH_VALUE_EMOJI_DOWNLOAD_CLICK);
//				}
//			});
//			container.addView(view);
//			return view;
//		} else if(bean.isType(EmojiPageBean.TYPE_GIF)) {
//            StickerGifBarView view = (StickerGifBarView) View.inflate(mContext, R.layout.image_edit_sticker_gif_bar, null);
//			if(!mStickerBar.isApply()) {
//				view.init();
//			}
//			view.setAutoScrollToPosition(mGifAutoScrollPosition);
//			mGifAutoScrollPosition = -1;
//			view.setOnGifItemClickListener(mOnGifItemClickListener);
//			container.addView(view);
//			return view;
        } else {
            return null;
        }
    }

    @Override
    public void destroyItem(ViewGroup view, int position, Object arg2) {
        view.removeView((View) arg2);
    }

    @Override
    public boolean isViewFromObject(View view, Object obj) {
        return (view == obj);
    }

    @Override
    public void restoreState(Parcelable arg0, ClassLoader arg1) {
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    public void refresh(int position) {
        mRefreshPosition = position;
        super.notifyDataSetChanged();
    }

    @Override
    public void notifyDataSetChanged() {
        mRefreshPosition = -1;
        super.notifyDataSetChanged();
    }

    /**
     * getView中View的类型增加时必须修改这个方法  不然广告会不正确
     */
    @Override
    public int getItemPosition(Object object) {
        if (mRefreshPosition == -1) {
            return POSITION_NONE;
        } else {
            View v = (View) object;
            if (v.getTag() != null) {
                int position = (int) v.getTag();
                if (position == mRefreshPosition) {
                    return POSITION_NONE;
                } else {
                    return POSITION_UNCHANGED;
                }
            } else {
                return POSITION_UNCHANGED;
            }
        }
    }

    private View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    };

}
